<!-- Created by henian.xu on 2018/8/13. -->

<template>
    <el-checkbox-group v-model="model">
        <el-checkbox
            v-for="(item) in listData"
            :key="item.id"
            :label="item.id"
        >{{ item.name }}
        </el-checkbox>
    </el-checkbox-group>
</template>

<script>
import emitter from 'element-ui/src/mixins/emitter';
import { Rs } from '@/api';

export default {
    name: 'CheckboxGroupAndOr',
    mixins: [emitter],
    data() {
        return {
            listData: [],
        };
    },
    props: {
        value: {
            type: [Number, String],
            required: true,
        },
        // 这个值是字典值的 Code1
        type: {
            type: String,
            default: '',
        },
        data: {
            type: Array,
            default() {
                return null;
            },
        },
    },
    watch: {
        data: {
            handler(val) {
                this.listData = val || [];
            },
            immediate: true,
        },
    },
    computed: {
        model: {
            get() {
                const { listData, value } = this;
                const res = [];
                if (!+value) return res;
                listData.forEach(item => {
                    if (item.id & +value) {
                        res.push(item.id);
                    }
                });
                return res;
            },
            set(val) {
                let value = 0;
                if (Array.isArray(val) || val.length) {
                    value = val.reduce((prev, curr) => {
                        return prev | curr;
                    }, 0);
                }
                this.$emit('input', value);
                this.dispatch('ElFormItem', 'el.form.change', [value]);
            },
        },
    },
    methods: {
        getListData() {
            return Rs.Dic.entry({ dicCode: this.type }).then(json => {
                // const str = json.data.data.reduce((prev, curr) => {
                //     prev.push({
                //         id: curr.id,
                //         name: curr.name,
                //     });
                //     return prev;
                // }, []);
                // console.log(this.type, this.$el, JSON.stringify(str));
                this.listData = json.data.data;
            });
        },
    },
    created() {
        const { data, type } = this;
        if (!data && !type) throw new Error('props: "type / data" 至少填写一个');
        if (type) {
            this.getListData();
        }
        // console.log(this.data);
    },
};
</script>

<style lang="scss">
</style>
